import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import loadjs from 'loadjs';
import WeaUtils from '../../public/wea-utils';
import { Button, Tools } from 'weaver-mobile';
import { Reply } from 'weaver-mobile-page';
import Utils from '../../public/wea-utils/index';
const NoMask = Reply.NoMask;
const getLabel = Tools.getLabel;
@withRouter
@inject('blogCommentStore')
@observer
export default class BlogWrite extends React.Component {

  componentDidMount() {
    const init = this.createEditor;
    loadjs.isDefined('ckeditorJS') ? loadjs.ready('ckeditorJS', init) :
    loadjs('/cloudstore/resource/pc/ckeditor-4.6.2/ckeditor.js', 'ckeditorJS', init);

    setTimeout(() => {
      let iframeWind = document.getElementById("cke_editorContanier").getElementsByTagName("iframe")[0].contentWindow;
      let imgArr = iframeWind.document.getElementsByTagName("img");
      Utils.addStyle(iframeWind,'.mobileBlogImgInnerTemp {max-width:100% !important;}');
      if(imgArr && imgArr.length > 0){
        for(let k=0; k<imgArr.length; k++){
          if(imgArr[k].naturalWidth > document.body.clientWidth){
            imgArr[k].setAttribute("class","mobileBlogImgInnerTemp");
          }
        }
      }  
    }, 800);
    // window.addEventListener("popstate", function() {
    //   console.log('addEventListener');					
    // });

  }

  componentWillMount() {
    const {blogCommentStore} = this.props;
    blogCommentStore.setRoutePath(this.props.location.pathname);
    blogCommentStore.setReplyConfig();
  }

  componentWillUnmount() {
    const store = this.getStore();
    store.clearBlogText();
  }

  getStore = () => {
    const {writeBlogStore, storeName} = this.props;
    return writeBlogStore[storeName] || writeBlogStore;
  }

  // ckEditor -- 初始化
  createEditor = () => {
    const store = this.getStore();
    const { blogText, setBlogText } = store;
    const config = { // 富文本配置
      toolbar:[
        { name: 'document', items: [ 'Source'] },
        { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
        { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
        { name: 'colors', items: [ 'TextColor' ] },
        { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
        { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
      ],
      toolbarCanCollapse: true,
      toolbarStartupExpanded: false,
      uploadUrl: '/api/blog/fileupload/uploadimage',
      extraPlugins: 'markdown',
      resize_enabled: false,
      allowedContent: true,
    };

    this.editor = window.CKEDITOR.replace('editorContanier', config);
    if (this.editor) { // 初始化数据
      this.editor.setData(blogText);
    }
    this.editor.on('change', e => { // 监听onChange事件
      const content = e.editor.getData();
      if (content) { setBlogText(content); }
    });
    this.editor.on('focus', e => { // 监听onFocus事件
      const replyRef = this.replyRef;
      if (replyRef) { replyRef.setVisible(false); }
    });
    this.editor.on('blur', e => { // 监听onBlur事件
    });
    this.editor.on('instanceReady', function (e) {//ck初始化完成事件
      let iframeWind = document.getElementById("cke_editorContanier").getElementsByTagName("iframe")[0].contentWindow;
      let iframeHtml = iframeWind.document.getElementsByTagName("html")[0];
      let iframeBody = iframeWind.document.getElementsByTagName("body")[0];
      iframeHtml.style.height = '100%';
      iframeBody.style.height = '100%';
    });
  }

  // ckEditor -- 插入 html
  insertHTML(html, position = 'selection', isClear, callback) { // isClear 是否清楚现有的数据
    const store = this.getStore();
    const { setBlogText } = store;
    const newHtml = html;
    // this.editor.focus(position); 
    const insert = () => {
      if (isClear) {
        this.editor.setData(newHtml, {
          callback: () => { typeof callback === 'function' && callback();},
        });
      } else {
        this.editor.insertHtml(html);
      }
      setBlogText(this.getData());
    };
    if (position === 'last') {
      this.timer_insert = setTimeout(() => {
        insert();
        this.timer_insert && clearTimeout(this.timer_insert);
      }, 200);
    } else insert();
  }

  getData() {
    if (this.editor) return this.editor.getData();
  }

  setData(value) {
    this.editor && this.editor.setData(value);
  }

  //  以下都是调用insertHTML方法，插入需要的html数据 (具体要什么样的html自定义)
  onEmojiChange = (emoji) => this.insertHTML(`<span>${emoji}</span>`)

  onImgChange = (datas) => {
    const { blogCommentStore: { writeReply } } = this.props;
    writeReply.doClear();
    datas.map(v => {
      this.insertHTML(`<img src=${v.imgSrc} class='mobileBlogImgInnerTemp' />`);
    })
  }

  onAtChange = (datas) => {
    datas.map(v => {
      this.insertHTML(`<a id=${v.id}>${v.name}</a>&nbsp;&nbsp;&nbsp;`)
    });
  }

  onBrowserChange = (key, datas) => {
    datas.map(v => {
      this.insertHTML(`<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" linktype="${key}" onclick="try{return openAppLink(this,${v.id});}catch(e){}">${v.name}</a>&nbsp;&nbsp;&nbsp;`);
    });
  }

  onUploadChange = (key, datas) => {
    datas.map(v => {
      this.insertHTML(`<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" onclick="try{opendoc1('${v.id}',this);return false;}catch(e){}">${v.name}</a>&nbsp;`);
      this.insertHTML(`<a href="javascript:void(0)" style="text-decoration:underline !important;" linkid="${v.id}" onclick="try{downloads('${v.id}',this,'${v.name}');return false;}catch(e){}">下载</a>&nbsp;&nbsp;&nbsp;`);
    });
  }

  onSpeechChange = (datas) => {
    this.insertHTML(`<span>${datas}</span>`)
  }

  // 提交微博
  blogSubmit = () => {
    const { history, match } = this.props;
    const store = this.getStore();
    const { saveOrUpdateBlog, blogText, replyComment} = store;
    const writeBlogDate = WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd');
    saveOrUpdateBlog({
      content: blogText,
      workdate: match.path.indexOf('writeBlog') === -1 ? replyComment.workdate : writeBlogDate,
      comefrom: 4
    }, () => {
      replyComment ? history.go(-1) : history.push('/myBlog/blog')
    })
  }
 
  render() {
    const { blogCommentStore: { writeReply } } = this.props;
    const store = this.getStore();
    const {replyComment, blogText, storeName, setBlogText} =store;

    const leftConfig = [
      { type: 'voice' },
      { type: 'blog-biaoqing' },
      { type: 'blog-tupian', model: 2 },
      //{ type: '@' },
      { type: 'tianjia' },
    ];

    return (
      <div className='blog-blogWrite' style={{height: '100%'}}>
        <div className='blog-blogWrite-container'>
          <div className='blog-blogWrite-container-editor'>
            <div id="editorContanier" ref="editor" />
          </div>
          <NoMask
            ref={ref => this.replyRef = ref}
            store={writeReply}
            showInput={false}
            leftConfig={leftConfig}
            visible={false}
            onEmojiChange={this.onEmojiChange}
            onImgChange={this.onImgChange}
            onAtChange={this.onAtChange}
            onBrowserChange={this.onBrowserChange}
            onUploadChange={this.onUploadChange}
            onSpeechChange={this.onSpeechChange}
          />
        </div>
        <Button type="primary" 
          disabled={blogText ? false : true}
          onClick={this.blogSubmit}
        >{getLabel(30986, '保存')}</Button>
      </div>
    );
  }
}